package com.hsteach.service.buildingApply;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.ListMultimap;
import com.google.common.collect.Lists;
import com.hsteach.common.config.App;
import com.hsteach.common.config.AppConfig;
import com.hsteach.common.core.domain.model.AuthInfo;
import com.hsteach.common.core.page.TableDataInfo;
import com.hsteach.common.exception.ServiceException;
import com.hsteach.common.utils.DateUtils;
import com.hsteach.common.utils.SecurityUtils;
import com.hsteach.common.utils.StringUtils;
import com.hsteach.common.utils.uuid.UUID;
import com.hsteach.dao.domain.buildingApply.BuildingApply;
import com.hsteach.dao.domain.buildingApply.BuildingReviewPerson;
import com.hsteach.dao.mapper.buildingApply.BuildingApplyMapper;
import com.hsteach.dao.mapper.buildingApply.BuildingReviewPersonMapper;
import com.hsteach.enums.*;
import com.hsteach.framework.feign.client.xgk.dto.GetPersonBySpyCodeEntity;
import com.hsteach.framework.feign.client.xgk.dto.ret.GetClassRoomListByPlaceIdRet;
import com.hsteach.framework.feign.client.xgk.dto.ret.GetPersonBySpyCodeRet;
import com.hsteach.framework.feign.client.xgk.dto.ret.GetTeacherRet;
import com.hsteach.service.third.MessageService;
import com.hsteach.service.third.XgkService;
import com.hsteach.util.BuildingNameComparator;
import com.hsteach.util.FloorNameComparator;
import com.hsteach.web.controller.buildingApply.dto.*;
import com.hsteach.web.controller.buildingApply.vo.ListBuildingApplyVo;
import com.hsteach.web.controller.buildingApply.vo.ListHoldingTimeVo;
import com.hsteach.web.controller.buildingApply.vo.ListRoomsVo;
import com.hsteach.web.controller.buildingApply.vo.ListTimetableVo;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.function.Function;
import java.util.stream.Collectors;

/**
 * 场所申请Service业务层处理
 *
 * @author fanxquer
 * @date 2023-08-25
 */
@Service
@Slf4j
public class BuildingApplyService
{
    @Autowired
    private BuildingApplyMapper buildingApplyMapper;

    @Autowired
    private BuildingReviewPersonMapper buildingReviewPersonMapper;

    @Autowired
    private List<RepeatApplyHandler> repeatApplyHandlers;

    @Autowired
    private XgkService xgkService;

    @Autowired
    private MessageService messageService;

    @Autowired
    private AppConfig appConfig;

    private static final SimpleDateFormat SDF = new SimpleDateFormat("yyyy-MM-dd");
    private static final SimpleDateFormat SDF2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    private static final SimpleDateFormat SDF3 = new SimpleDateFormat("HH:mm");

    /**
     * 查询场所申请
     *
     * @param id 场所申请主键
     * @return 场所申请
     */
    public BuildingApply selectBuildingApplyById(Long id)
    {
        return buildingApplyMapper.selectBuildingApplyById(id);
    }

    /**
     * 查询场所申请列表
     *
     * @param dto 条件
     * @return 场所申请
     */
    public List<BuildingApply> listBuildingApply(ListBuildingApplyDto dto, String personId, ApplyTypeEnum typeEnum)
    {
        TimeEnum byCode = TimeEnum.getByCode(dto.getSearchDate());
        Calendar endDate = Calendar.getInstance();
        // 设置为今日0点
        endDate.setTime(DateUtils.getNowyyyyMMdd());
        endDate.add(byCode.getCalendarType(), byCode.getOffset());
        BuildingApply query = new BuildingApply();
        if (byCode != TimeEnum.ALL) {
            query.setBeginDate(endDate.getTime());
        }
        query.setSearchStatus(dto.getStatus());
        query.setOrgCode(SecurityUtils.getAuthInfo().getOrgCode());
        query.setPersonId(personId);
        query.setApplyType(typeEnum.getCode());
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        return buildingApplyMapper.listBuildingApply(query);
    }

    public TableDataInfo<ListBuildingApplyVo> listMine(ListBuildingApplyDto dto, ApplyTypeEnum type, String personId) {
        if (StringUtils.isEmpty(personId)) {
            personId = "-1";
        }
        List<BuildingApply> buildingApplies = listBuildingApply(dto, personId, type);
        Long total = new PageInfo(buildingApplies).getTotal();
        List<ListBuildingApplyVo> ret = buildingApplies.stream().map(e -> {
            ListBuildingApplyVo vo = new ListBuildingApplyVo();
            BeanUtils.copyProperties(e, vo);
            return vo;
        }).collect(Collectors.toList());
        TableDataInfo tableDataInfo = new TableDataInfo(ret, total);

        return tableDataInfo;
    }

    public TableDataInfo<ListBuildingApplyVo> listReview(ListReviewDto dto, ApplyTypeEnum type) {
        AuthInfo authInfo = SecurityUtils.getAuthInfo();

        BuildingApply query = new BuildingApply();
        query.setApplyType(type.getCode());
        if (BooleanEnum.FALSE.getCode().equals(dto.getApplyStatus())) {
            // 查询可审核类型
            List<String> buildingUses = getReviewUse(type, authInfo);
            if (buildingUses.size() == 0) {
                TableDataInfo tableDataInfo = new TableDataInfo(Lists.newArrayList(), 0);
                return tableDataInfo;
            }
            query.setSGtBeginDate(DateUtils.getNowyyyyMMdd());
            query.setSGtBeginTime(new Date());
            query.setSBuildingUses(buildingUses);
            query.setSearchStatus(Lists.newArrayList(ApplyStatusEnum.APPLY.getCode()));
        } else if (BooleanEnum.TRUE.getCode().equals(dto.getApplyStatus())) {
            query.setSearchStatus(Lists.newArrayList(ApplyStatusEnum.REJECT.getCode(), ApplyStatusEnum.PASS.getCode()));
            query.setSReview(authInfo.getPersonId());
        } else {
            // 查询可审核类型
            List<String> buildingUses = getReviewUse(type, authInfo);
            if (buildingUses.size() == 0) {
                TableDataInfo tableDataInfo = new TableDataInfo(Lists.newArrayList(), 0);
                return tableDataInfo;
            }
            query.setSGtBeginDate(DateUtils.getNowyyyyMMdd());
            query.setSGtBeginTime(new Date());
            query.setSBuildingUses(buildingUses);
            query.setSearchStatus(Lists.newArrayList(ApplyStatusEnum.APPLY.getCode(), ApplyStatusEnum.REJECT.getCode(), ApplyStatusEnum.PASS.getCode()));
            query.setSReview(authInfo.getPersonId());
        }
        query.setOrgCode(authInfo.getOrgCode());
        query.setTimeModes(Lists.newArrayList(0,1));
        PageHelper.startPage(dto.getPageNum(), dto.getPageSize());
        List<BuildingApply> buildingApplies = buildingApplyMapper.selectBuildingApplyReviewList(query);
        Long total = new PageInfo(buildingApplies).getTotal();
        List<ListBuildingApplyVo> ret = buildingApplies.stream().map(e -> {
            ListBuildingApplyVo vo = new ListBuildingApplyVo();
            BeanUtils.copyProperties(e, vo);
            if (ApplyStatusEnum.APPLY.getCode().equals(e.getCurStatus())) {
                vo.setApplyStatus(BooleanEnum.FALSE.getCode());
            } else {
                vo.setApplyStatus(BooleanEnum.TRUE.getCode());
            }
            if (BooleanEnum.TRUE.getCode().equals(e.getRepeatStatus()) && e.getRepeatBeginDate() != null) {
                Calendar date = Calendar.getInstance();
                date.setTime(e.getRepeatBeginDate());
                Calendar beginTime = Calendar.getInstance();
                beginTime.setTime(vo.getBeginTime());
                beginTime.set(date.get(Calendar.YEAR), date.get(Calendar.MONTH), date.get(Calendar.DAY_OF_MONTH));
                vo.setBeginTime(beginTime.getTime());
            }
            return vo;
        }).collect(Collectors.toList());
        TableDataInfo tableDataInfo = new TableDataInfo(ret, total);
        return tableDataInfo;
    }

    private List<String> getReviewUse(ApplyTypeEnum type, AuthInfo authInfo) {
        BuildingReviewPerson configQuery = new BuildingReviewPerson();
        configQuery.setApplyType(type.getCode());
        configQuery.setOrgCode(authInfo.getOrgCode());
        configQuery.setReviewPersonId(authInfo.getPersonId());
        List<BuildingReviewPerson> configs = buildingReviewPersonMapper.selectBuildingReviewPersonList(configQuery);
        return configs.stream().map(BuildingReviewPerson::getBuildingUse).collect(Collectors.toList());
    }

    public List<ListHoldingTimeVo> listHoldingTime(ListHoldingTimeDto dto) {
        return listHoldingTime(dto.getBeginDate(), Lists.newArrayList(dto.getBuildingId()));
    }

    public List<ListTimetableVo> listTimetable(ListTimetableDto dto) {
        return Lists.newArrayList(
                new ListTimetableVo("07:00", "07:50", "早自习"),
                new ListTimetableVo("08:00", "08:50", "第一节"),
                new ListTimetableVo("09:00", "09:50", "第二节"),
                new ListTimetableVo("10:00", "10:50", "第三节"),
                new ListTimetableVo("11:00", "11:50", "第四节"),
                new ListTimetableVo("11:50", "13:00", "午休"),
                new ListTimetableVo("13:00", "13:50", "第五节"),
                new ListTimetableVo("14:00", "14:50", "眼保健操"),
                new ListTimetableVo("15:00", "15:50", "第六节"),
                new ListTimetableVo("16:00", "16:50", "第七节"),
                new ListTimetableVo("17:00", "17:50", "第八节"),
                new ListTimetableVo("17:50", "18:00", "晚餐"),
                new ListTimetableVo("18:00", "18:50", "晚自习"),
                new ListTimetableVo("19:00", "19:50", "第九节"),
                new ListTimetableVo("20:00", "20:50", "第十节")

        );
//        List<QuerySinglePlaceTableRet> querySinglePlaceTableRets = xgkService.querySinglePlaceTable(dto.getBuildingId(), DateUtils.parseDateToStr(DateUtils.YYYY_MM_DD, dto.getDate()));
//        List<ListTimetableVo> ret = querySinglePlaceTableRets.stream()
//                .sorted(Comparator.comparing(QuerySinglePlaceTableRet::getTeachLesSortOptIndex, Comparator.comparingInt(Integer::valueOf)))
//                .map(e -> {
//            ListTimetableVo vo = new ListTimetableVo();
//            if (StringUtils.isNotEmpty(e.getLesTime())) {
//                String[] split = e.getLesTime().split("-");
//                vo.setBeginTime(Optional.ofNullable(split[0]).orElse(""));
//                vo.setEndTime(Optional.ofNullable(split[1]).orElse(""));
//            }
//            vo.setTeachLesSortOptName(e.getTeachLesSortOptName());
//            return vo;
//        }).collect(Collectors.toList());
//        return ret;
    }

    public List<ListRoomsVo> listRooms(String buildingId, Integer type, Date date) {
        List<GetClassRoomListByPlaceIdRet> rooms = xgkService.getClassRoomListByPlaceId(type, buildingId);
        rooms = rooms.stream().filter(e -> BuildingUseEnum.match(ApplyTypeEnum.BUILDING, e.getUseId())).collect(Collectors.toList());
        List<String> buildingIds = rooms.stream().map(GetClassRoomListByPlaceIdRet::getClassroomId).collect(Collectors.toList());
        List<ListHoldingTimeVo> listHoldingTimeVos = listHoldingTime(date, buildingIds);
        Map<String, List<ListHoldingTimeVo>> timeMap = listHoldingTimeVos.stream().collect(Collectors.groupingBy(ListHoldingTimeVo::getBuildingId));
        List<ListRoomsVo> ret = rooms.stream().map(e -> {
            ListRoomsVo vo = new ListRoomsVo();
            BeanUtils.copyProperties(e, vo);
            vo.setHoldTime(timeMap.getOrDefault(e.getClassroomId(), Lists.newArrayList()));
            return vo;
        }).collect(Collectors.toList());

        return ret.stream()
                .sorted(new BuildingNameComparator()
                        .thenComparing(new FloorNameComparator())
                        .thenComparing(ListRoomsVo::getRoomCodeAsInt, Comparator.nullsLast(Integer::compareTo)))
                .collect(Collectors.toList());
    }

    private List<ListHoldingTimeVo> listHoldingTime(Date beginDate, List<String> buildingIds) {
        BuildingApply query = new BuildingApply();
        query.setOrgCode(SecurityUtils.getAuthInfo().getOrgCode());
        query.setBeginDate(beginDate);
        query.setSearchStatus(Lists.newArrayList(ApplyStatusEnum.APPLY.getCode(), ApplyStatusEnum.PASS.getCode()));
        query.setBuildingIds(buildingIds);
        query.setTimeModes(Lists.newArrayList(0,1));
        List<BuildingApply> buildingApplies = buildingApplyMapper.selectBuildingApplyList(query);
        List<ListHoldingTimeVo> ret = buildingApplies.stream().map(e -> {
            ListHoldingTimeVo vo = new ListHoldingTimeVo();
            vo.setBeginTime(e.getBeginTime());
            vo.setEndTime(e.getEndTime());
            vo.setBuildingId(e.getBuildingId());
            return vo;
        }).collect(Collectors.toList());
        return ret;
    }

    /**
     * 新增场所申请
     *
     * @param buildingApply 场所申请
     * @return 结果
     */
    public int insertBuildingApply(BuildingApply buildingApply)
    {
        buildingApply.setCreateTime(DateUtils.getNowDate());
        return buildingApplyMapper.insertBuildingApply(buildingApply);
    }

    @Transactional(rollbackFor = Exception.class)
    public int buildingApply(AddBuildingApplyDto dto, ApplyTypeEnum type)
    {
        // 没有场所时使用不占用时间线的方式
        if (StringUtils.isEmpty(dto.getBuildingId())) {
            dto.setTimeMode(-1);
        }
        BuildingApply apply = new BuildingApply();
        BeanUtils.copyProperties(dto, apply);
        AuthInfo authInfo = SecurityUtils.getAuthInfo();
        apply.setCreateByName(authInfo.getName());
        apply.setCreateBy(authInfo.getPersonId());
        apply.setCreateTime(DateUtils.getNowDate());
        apply.setPersonId(authInfo.getPersonId());
        apply.setCurStatus(ApplyStatusEnum.APPLY.getCode());
        apply.setDelStatus(BooleanEnum.TRUE.getCode());
        apply.setOrgCode(authInfo.getOrgCode());
        apply.setApplyName(apply.getBuildingName());
        apply.setBeginDate(apply.getBeginTime());
        apply.setRepeatBeginDate(apply.getBeginTime());
        UUID uuid = UUID.fastUUID();
        String repeatId = uuid.toString(true);
        apply.setRepeatId(repeatId);

        int i;
        // 重复申请处理
        if (BooleanEnum.TRUE.getCode().equals(dto.getRepeatStatus())) {
            RepeatApplyHandler repeatApplyHandler = repeatApplyHandlers.stream().filter(e -> e.getType().getCode().equals(dto.getRepeatType())).findFirst().orElse(null);
            if (repeatApplyHandler == null) {
                throw new ServiceException("重复申请处理错误");
            }
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(dto.getRepeatEndDate());
            calendar.add(Calendar.DATE, 1);
            List<BuildingApply> repeatList = repeatApplyHandler.handle(apply, dto.getBeginTime(), calendar.getTime());
            String id = uuid.toString(true);
            repeatList.stream().forEach(e -> {
                e.setRepeatId(id);
            });
            if (repeatList.size() > 0) {
                if (StringUtils.isNotEmpty(dto.getBuildingId())) {
                    // 校验时间段是否有其他预约
                    validApply(repeatList);
                }
                try {
                    // 发送审核通知
                    sendMsg(repeatList.get(0));
                } catch (Exception e) {

                }
                i = buildingApplyMapper.batchInsert(repeatList);
            } else {
                throw new ServiceException("重复申请处理错误");
            }
        } else {
            if (StringUtils.isNotEmpty(dto.getBuildingId())) {
                // 校验时间段是否有其他预约
                validApply(Lists.newArrayList(apply));
            }
            try {
                // 发送审核通知
                sendMsg(apply);
            } catch (Exception e) {
                log.error("发送信息失败", e);
            }
            i = buildingApplyMapper.insertBuildingApply(apply);
        }
        return i;
    }

    private void sendMsg(BuildingApply apply) {
        BuildingReviewPerson query = new BuildingReviewPerson();
        query.setApplyType(ApplyTypeEnum.BUILDING.getCode());
        query.setBuildingUse(apply.getBuildingUse());
        query.setOrgCode(SecurityUtils.getAuthInfo().getOrgCode());
        List<String> reviewPeople = buildingReviewPersonMapper.selectBuildingReviewPersonList(query).stream().map(BuildingReviewPerson::getReviewPersonId).collect(Collectors.toList());
        App app = appConfig.getConfig().get(SecurityUtils.getAuthInfo().getAppId());
        if (app != null && CollectionUtils.isNotEmpty(reviewPeople)) {
            String title = SecurityUtils.getAuthInfo().getName()
                    + "申请预约" +  Optional.ofNullable(apply.getParentBuildingName()).orElse("") + " " + apply.getBuildingName();
            String msg;
            if (BooleanEnum.TRUE.getCode().equals(apply.getRepeatStatus())) {
                msg = title + "，日期" + DateUtils.parseDateToStr("MM-dd", apply.getRepeatBeginDate()) + "至" + DateUtils.parseDateToStr("MM-dd", apply.getRepeatEndDate())
                        + "，时间" + DateUtils.parseDateToStr("HH:mm", apply.getBeginTime()) + "-" + DateUtils.parseDateToStr("HH:mm", apply.getEndTime());
            } else {
                msg = title + "，日期" + DateUtils.parseDateToStr("MM-dd", apply.getBeginTime())
                        + "，时间" + DateUtils.parseDateToStr("HH:mm", apply.getBeginTime()) + "-" + DateUtils.parseDateToStr("HH:mm", apply.getEndTime());
            }
            String params = "&type=2";
            String url = app.getRedirectUrl() + params;
            String content = "<p>" + msg + "<a href=\"" + url + "\">跳转进应用</a></p>";
            List<GetTeacherRet> teachers = xgkService.getTeachers(SecurityUtils.getAuthInfo().getId());
            Map<String, String> teacherMap = teachers.stream().filter(e -> e.getT_userID() != null).collect(Collectors.toMap(GetTeacherRet::getPersonId, GetTeacherRet::getT_userID, (v1, v2) -> v2));
            List<String> tPersonId = Lists.newArrayList();
            for (String personId : reviewPeople) {
                if (teacherMap.containsKey(personId)) {
                    tPersonId.add(teacherMap.get(personId));
                }
            }
            messageService.sendMsg(content, tPersonId, MsgTypeEnum.BUILDING_REVIEW_NOTIFY, title);
        }
    }

    private boolean validApply(List<BuildingApply> applies) {
        List<String> buildIds = applies.stream().map(BuildingApply::getBuildingId).collect(Collectors.toList());
        List<Date> dates = applies.stream().map(e -> {
            String format = SDF.format(e.getBeginDate());
            try {
                return SDF.parse(format);
            } catch (ParseException ex) {
                throw new ServiceException(ex.getMessage());
            }
        }).collect(Collectors.toList());
        List<BuildingApply> buildingApplies = buildingApplyMapper.selectByDateAndBuildId(SecurityUtils.getAuthInfo().getOrgCode(), dates, buildIds);
        buildingApplies.stream().forEach(e -> {
            for (int i = 0;i < applies.size();i++) {
                BuildingApply apply = applies.get(i);
                // 申请开始时间在其他申请时间范围内或者结束时间在其他申请时间范围内，则校验不通过
                if ((apply.getBeginTime().compareTo(e.getBeginTime()) > 0 && apply.getBeginTime().compareTo(e.getEndTime()) < 0)
                    || (apply.getEndTime().compareTo(e.getBeginTime()) > 0 && apply.getEndTime().compareTo(e.getEndTime()) < 0)) {
                    String error = apply.getBuildingName() + "场馆"  + SDF3.format(apply.getBeginDate()) + "-" +
                            SDF3.format(apply.getEndTime()) + "时间段已被预约，请重新预约";
                    throw new ServiceException(error);
                }

                // 校验完全相同的时间
                if (apply.getBeginTime().compareTo(e.getBeginTime()) == 0 && apply.getEndTime().compareTo(e.getEndTime()) == 0) {
                    String error = apply.getBuildingName() + "场馆" + SDF3.format(apply.getBeginDate()) + "-" +
                            SDF3.format(apply.getEndTime()) + "时间段已被预约，请重新预约";
                    throw new ServiceException(error);
                }
            }
        });
        return true;
    }

    /**
     * 修改场所申请
     *
     * @param buildingApply 场所申请
     * @return 结果
     */
    public int updateBuildingApply(BuildingApply buildingApply)
    {
        buildingApply.setUpdateTime(DateUtils.getNowDate());
        return buildingApplyMapper.updateBuildingApply(buildingApply);
    }

    public int review(ReviewDto dto) {
        AuthInfo authInfo = SecurityUtils.getAuthInfo();

        BuildingApply update = new BuildingApply();
        update.setId(dto.getId());
        update.setReviewBy(authInfo.getPersonId());
        update.setReviewByName(authInfo.getName());
        update.setCurStatus(dto.getReviewStatus());
        update.setRejectReason(dto.getRejectReason());
        BuildingApply buildingApply = buildingApplyMapper.selectBuildingApplyById(dto.getId());
        if (!ApplyStatusEnum.APPLY.getCode().equals(buildingApply.getCurStatus())) {
            throw new ServiceException("该申请状态已变更，请刷新页面后处理");
        }
        if (!BuildStatusEnum.START.getCode().equals(buildingApply.getStatus())) {
            throw new ServiceException("该申请进行状态已变更，请刷新页面后处理");
        }
        if (BooleanEnum.TRUE.getCode().equals(buildingApply.getRepeatStatus())) {
            update.setRepeatId(buildingApply.getRepeatId());
            buildingApplyMapper.updateByRepeatId(update);
        } else {
            buildingApplyMapper.updateBuildingApply(update);
        }
        try {
            sendReviewMsg(buildingApply, dto.getReviewStatus());
        } catch (Exception e) {
            log.error("发送信息失败", e);
        }
        return 1;
    }

    private void sendReviewMsg(BuildingApply apply, Integer status) {
        App app = appConfig.getConfig().get(SecurityUtils.getAuthInfo().getAppId());
        if (app == null) {
            return;
        }
        String title =  Optional.ofNullable(apply.getParentBuildingName()).orElse("") + " " + apply.getBuildingName();
        if (ApplyStatusEnum.PASS.getCode().equals(status)) {
            title = title + "申请审批已通过";
        }

        if (ApplyStatusEnum.REJECT.getCode().equals(status)) {
            title = title + "申请审批已拒绝";
        }

        String msg;
        if (BooleanEnum.TRUE.getCode().equals(apply.getRepeatStatus())) {
            msg = "申请时间为" + DateUtils.parseDateToStr("MM-dd", apply.getRepeatBeginDate()) + "至" + DateUtils.parseDateToStr("MM-dd", apply.getRepeatEndDate())
                    + " " + DateUtils.parseDateToStr("HH:mm", apply.getBeginTime()) + "-" + DateUtils.parseDateToStr("HH:mm", apply.getEndTime());
        } else {
            msg = "申请时间为" + DateUtils.parseDateToStr("MM-dd", apply.getBeginTime())
                    + " " + DateUtils.parseDateToStr("HH:mm", apply.getBeginTime()) + "-" + DateUtils.parseDateToStr("HH:mm", apply.getEndTime());
        }

        String params = "&type=1";
        String url = app.getRedirectUrl() + params;
        String content = "<p>" + msg + "<a href=\"" + url + "\">跳转进应用</a></p>";
        List<GetTeacherRet> teachers = xgkService.getTeachers(SecurityUtils.getAuthInfo().getId());
        Map<String, String> teacherMap = teachers.stream().filter(e -> e.getT_userID() != null).collect(Collectors.toMap(GetTeacherRet::getPersonId, GetTeacherRet::getT_userID, (v1, v2) -> v2));

        if (teacherMap.containsKey(apply.getPersonId())) {
            messageService.sendMsg(content, Lists.newArrayList(teacherMap.get(apply.getPersonId())), MsgTypeEnum.BUILDING_REVIEW_NOTIFY, title);
        }
    }

    /**
     * 批量删除场所申请
     *
     * @param ids 需要删除的场所申请主键
     * @return 结果
     */
    public int deleteBuildingApplyByIds(Long[] ids)
    {
        return buildingApplyMapper.deleteBuildingApplyByIds(ids);
    }

    public int cancelApply(CancelApplyDto dto)
    {
        BuildingApply apply = buildingApplyMapper.selectBuildingApplyById(dto.getId());
        int i;
        if (new Integer(1).equals(dto.getCancelType())) {
            if (StringUtils.isNotEmpty(apply.getRepeatId())) {
                BuildingApply query = new BuildingApply();
                query.setRepeatId(apply.getRepeatId());
                query.setOrgCode(SecurityUtils.getAuthInfo().getOrgCode());
                query.setGtBeginDate(DateUtils.getNowyyyyMMdd());
                query.setGtBeginTime(new Date());
                query.setSearchStatus(Lists.newArrayList(ApplyStatusEnum.APPLY.getCode(), ApplyStatusEnum.PASS.getCode()));
                List<BuildingApply> buildingApplies = buildingApplyMapper.selectBuildingApplyList(query);
                List<Long> ids = buildingApplies.stream().map(BuildingApply::getId).collect(Collectors.toList());
                i = buildingApplyMapper.batchCancel(ids);
            }
            return 1;
        } else {
            if (ApplyStatusEnum.CANCEL.getCode().equals(apply.getStatus())) {
                throw new ServiceException("不能重复取消");
            }
            if (apply.getBeginTime().getTime() < System.currentTimeMillis()) {
                throw new ServiceException("该申请已开始，无法取消");
            }
            apply.setCurStatus(ApplyStatusEnum.CANCEL.getCode());
            i = buildingApplyMapper.updateBuildingApply(apply);
        }
        return i;
    }

    /**
     * 删除场所申请信息
     *
     * @param id 场所申请主键
     * @return 结果
     */
    public int deleteBuildingApplyById(Long id)
    {
        return buildingApplyMapper.deleteBuildingApplyById(id);
    }


}
